<template>
  <div class="chart" ref="chartWrapRef">
    <div>
      <h4 v-if="$slots.title" style="marginbottom: 20px">
        <slot name="title" />
      </h4>
      <h4 v-else-if="title" style="marginbottom: 20px">
        {{ title }}
      </h4>
      <chart
        ref="chartRef"
        :option="chartOption"
        :style="{ height: chartHeight }"
        @zrender:click="renderClickHandle"
      />
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, watch, computed, onMounted } from 'vue';
import { Chart } from '@/components';
import { getDataZoomVisibie, getDatazoomEnd } from '@/components/charts/util';
export default defineComponent({
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    height: {
      type: Number,
      default: 300,
    },
    fieldNames: {
      type: Object,
      default: () => ({
        name: 'name',
        value: 'value',
      }),
    },
    title: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: '智能',
    },
    defalutOptions: {},
  },
  setup(props, { emit }) {
    const barWidth = 10;
    const chartOption = ref({
      color: props.type == '智能' ? '#E99220' : props.type == '传统' ? '#3191FF' : '#1CCAFF',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        top: 20,
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      dataZoom: [
        {
          id: 'dataZoomX',
          show: true,
          showDataShadow: 'auto',
          xAxisIndex: [0],
          filterMode: 'filter',
          start: 0,
          end: 100,
          orient: 'horizontal',
          zoomLock: true,
          height: 15,
          bottom: 0,
          borderColor: 'transparent', //  边框颜色
        },
      ],
      xAxis: {
        type: 'category',
        data: [],
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          interval: 'auto',
          inside: false,
          verticalAlign: 'middle',
          rotate: 30, // 角度
        },
      },
      yAxis: {
        minInterval: 1,
        type: 'value',
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      series: {
        type: 'bar',
        barWidth: barWidth,
        itemStyle: {
          normal: {
            label: {
              show: true,
              position: 'top',
              rotate: 0,
              textStyle: {
                fontWeight: 'bolder',
                fontSize: '12',
              },
            },
          },
        },
        data: [],
      },
    });

    const chartHeight = computed(() => `${props.height}px`);
    const chartRef = ref();
    const chartWrapRef = ref();

    const setChartOption = data => {
      const xAxis = [];
      const seriesData = [];
      data.forEach(item => {
        const name = item[props.fieldNames.name];
        const value = item[props.fieldNames.value];
        const seriesItem = {
          name,
          value,
        };
        Object.keys(item).forEach(
          o =>
            ![props.fieldNames.name, props.fieldNames.value].includes(o) &&
            (seriesItem[o] = item[o]),
        );

        xAxis.push(name);
        seriesData.push(seriesItem);
      });
      chartOption.value.xAxis.data = xAxis;
      chartOption.value.series.data = seriesData;
      chartOption.value.dataZoom[0].show = getDataZoomVisibie(chartWrapRef.value, data.length);
      if (data.length > 7) {
        chartOption.value.dataZoom[0].end = 1000;
        chartOption.value.series.barWidth = 10;
        chartOption.value.series.itemStyle.normal.label.rotate = 40;
      } else {
        chartOption.value.dataZoom[0].end = getDatazoomEnd(chartWrapRef.value, data.length);
        chartOption.value.series.barWidth = 30;
        chartOption.value.series.itemStyle.normal.label.rotate = 0;
      }
      return {
        ...Object.assign(chartOption.value, props.defalutOptions),
      };
    };

    const renderClickHandle = e => {
      if (e?.topTarget?.type === 'Rect') {
        const index = chartRef.value.getIndexByEvent(e);
        const item = props.data[index];
        emit('zrender:click', index, item);
      }
    };

    watch(
      () => props.data,
      () => {
        setChartOption(props.data);
      },
    );
    watch(
      () => props.type,
      () => {
        let color = props.type == '智能' ? '#E99220' : props.type == '传统' ? '#3191FF' : '#1CCAFF';
        chartOption.value.color = color;
        setChartOption(props.data);
      },
    );

    onMounted(() => {
      setChartOption(props.data);
    });

    return {
      chartOption,
      chartHeight,
      setChartOption,
      chartRef,
      chartWrapRef,
      renderClickHandle,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style scoped></style>
